﻿using System.Configuration;
using System.IO;
using System.Reflection;
using System.ServiceProcess;
using log4net;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Patriq.Msmq.Router.Core;

namespace Patriq.Msmq.Router.Service
{
    public partial class MsmqRouterService : ServiceBase
    {
        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private readonly IRouteEngine routeEngine;

        public MsmqRouterService()
        {
            InitializeComponent();

            var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var configPath = Path.Combine(basePath, "log4net.xml");
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath));
            Logger.Info("Initializing the MsmqRouterService");

            var container = new UnityContainer();
            var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Configure(container);
            routeEngine = container.Resolve<IRouteEngine>();
        }

        protected override void OnStart(string[] args)
        {
            Logger.Info("Starting up");
            routeEngine.Start();
        }

        protected override void OnStop()
        {
            Logger.Info("Shutting down");
            routeEngine.Stop();
        }
    }
}
